package com.example.base.tools.upgrade

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.example.base.repository.BaseRepository
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Retrofit
import java.lang.Exception
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**  下载 Repository  **/
class DownloadRepository : BaseRepository() {

    var downloadInfo: DownloadInfo? = null
    var downloadListener: DownloadListener? = null

    private val downloadService: DownloadService by lazy {
        Retrofit.Builder()
            .baseUrl("http://127.0.0.1")
            .client(createClient())
            .build()
            .create(DownloadService::class.java)
    }

    /**  创建 OkHttpClient  **/
    private fun createClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(50000L, TimeUnit.MILLISECONDS)
            .readTimeout(10_000, TimeUnit.MILLISECONDS)
            .writeTimeout(30_000, TimeUnit.MILLISECONDS)
            .addInterceptor(DownloadInterceptor(downloadInfo!!, downloadListener))
            .build()
    }

    suspend fun downloadNewVersionAPK() = withContext(Dispatchers.IO) {
        //try {
            val responseBody = downloadService.downloadNewVersionAPK(
                "bytes=${downloadInfo!!.startPoint}-",
                downloadInfo!!.targetFileUrl
            )

            FileWriteTool.writeToDisk(responseBody, downloadInfo!!) {
                onCompleted {
                    withContext(Dispatchers.Main) {
                        downloadListener?.onCompleted()
                    }
                }

                onFailed {
                    withContext(Dispatchers.Main) {
                        downloadListener?.onFailed(it)
                    }
                }
            }

            suspendCoroutine<ResponseBody> { continuation ->
                continuation.resume(responseBody)
            }
       /* } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                downloadListener?.onFailed(e)
            }
        }*/
    }

}